package com.liyuxiang.filter;

import com.alibaba.fastjson.JSON;
import com.liyuxiang.pojo.entity.LoginUser;
import com.liyuxiang.utils.JwtUtil;
import com.liyuxiang.utils.RedisCache;
import com.liyuxiang.utils.WebUtils;
import com.liyuxiang.vm.ResponseResult;
import com.liyuxiang.vm.enums.ResultStatusEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.codec.DecodingException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }
        Long loginUserId;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            loginUserId = Long.valueOf(claims.getSubject());
        } catch (ExpiredJwtException e) {
            WebUtils.renderString(response, JSON.toJSONString(ResponseResult.errorResult(401, "此token已过期")));
            return;
        } catch (DecodingException e) {
            WebUtils.renderString(response, JSON.toJSONString(ResponseResult.errorResult(401, "token错误")));
            return;
        } catch (MalformedJwtException e) {
            WebUtils.renderString(response, JSON.toJSONString(ResponseResult.errorResult(401, "token校验失败")));
            return;
        } catch (SignatureException e) {
            WebUtils.renderString(response, JSON.toJSONString(ResponseResult.errorResult(401, "非有效的token")));
            return;
        } catch (Exception e) {
            WebUtils.renderString(response, JSON.toJSONString(ResponseResult.errorResult(401, "token未知异常")));
            return;
        }
        LoginUser loginUser = redisCache.getCacheObject("blogLogin" + loginUserId);
        //如果redis获取不到   说明redis过期了
        if (loginUser == null) {
            WebUtils.renderString(response, JSON.toJSONString(ResponseResult.errorResult(ResultStatusEnum.NEED_LOGIN)));
            return;
        }
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request, response);
        //从SercurityContextHolder
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//        Map<String, Object> cacheMap = redisCache.getCacheMap(loginUser.getUsername());

    }
}
